package thradLocal;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.LongAccumulator;

/**
 * @author ZhuQi
 * @ClassName Demo
 * @Date 2022/9/19 15:39
 * @Version 1.0
 * @Description 测试 ThreadLocal
 * 需求: 10个销售买房子，最后总计总共卖了多少
 */
@Slf4j
public class Demo {
    @SneakyThrows
    public static void main(String[] args) {
        int threadCount = 10;
        Hose hose = new Hose();
        final LongAccumulator totalCount = new LongAccumulator(Long::sum, 0L);
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                try {
                    int nextInt = ThreadLocalRandom.current().nextInt(10);
                    for (int i1 = 0; i1 < nextInt; i1++) {
                        hose.salHose();
                    }
                    totalCount.accumulate(hose.hoseCount.get());
                    log.info("当前线程卖掉了:{} nextInt:{}", hose.hoseCount.get(), nextInt);
                } finally {
                    hose.hoseCount.remove();
                }
                countDownLatch.countDown();
            }, "thread" + i).start();
        }
        countDownLatch.await();
        log.info("总计销售:{}", totalCount.get());
    }
}

class Hose {
    ThreadLocal<Integer> hoseCount = ThreadLocal.withInitial(() -> 0);

    /**
     * 卖房子
     */
    public int salHose() {
        hoseCount.set(hoseCount.get() + 1);
        return hoseCount.get();
    }
}